package island

import (
	"time"
)

const (
	StatusRunning    = "Running"
	StatusCreated    = "Created"
	StatusExited     = "Exited"
	StatusRemoving   = "Removing"
	StatusDead       = "Dead"
	StatusRestarting = "Restarting"
	StatusPaused     = "Paused"
)

type State struct {
	Running    bool          `json:"running"`
	Paused     bool          `json:"paused"`
	Restarting bool          `json:"restarting"`
	Exited     bool          `json:"exited"`
	Created    bool          `json:"created"`
	CreateTime time.Time     `json:"create_time"` // 容器创建时间 在第一次 save 的时候设置
	StartTime  time.Time     `json:"start_time"`  // 开始运行的时间 在 setRunning 的时候设置
	FinishTime time.Time     `json:"finish_time"` // 容器结束的时间 在 setStopped 的时候设置
	waitStop   chan struct{} // 等待 stop 的 channel
	waitRemove chan struct{} // 等待 remove 的 channel
}

func NewState() *State {
	return &State{
		waitStop:   make(chan struct{}),
		waitRemove: make(chan struct{}),
	}
}

func (s *State) String() string {
	if s.Restarting {
		return StatusRestarting
	} else if s.Running {
		if s.Paused {
			return StatusPaused
		}
		return StatusRunning
	} else if s.Created {
		return StatusCreated
	}

	return StatusExited
}

func (s *State) IsRunning() bool {
	return s.Running
}

func (s *State) SetRunning() {
	s.stateFalse()
	s.Running = true
	s.StartTime = time.Now().UTC()
}

func (s *State) SetCreated() {
	s.stateFalse()
	s.Created = true
	s.CreateTime = time.Now().UTC()
}

// 虽然 pause 了 但是 process 还是运行的所以是 running
func (s *State) SetPaused() {
	s.stateFalse()
	s.Running = true
	s.Paused = true
}

func (s *State) SetStopped() {
	s.stateFalse()
	s.Exited = true
	close(s.waitStop)
	s.waitStop = make(chan struct{})
	s.FinishTime = time.Now().UTC()
}

func (s *State) SetRestarting() {
	s.stateFalse()
	s.Restarting = true
	s.FinishTime = time.Now().UTC()
	close(s.waitStop)
	s.waitStop = make(chan struct{})
}

func (s *State) IsPaused() bool {
	return s.Paused
}

func (s *State) IsRestarting() bool {
	return s.Restarting
}

func (s *State) SetRemoved() {
	close(s.waitRemove)
	s.waitRemove = make(chan struct{})
}

func (s *State) WaitStop() chan struct{} {
	return s.waitStop
}

func (s *State) WaitRemove() chan struct{} {
	return s.waitRemove
}

func (s *State) stateFalse() {
	s.Running = false
	s.Created = false
	s.Paused = false
	s.Restarting = false
	s.Exited = false
}
